package com.ptadmin.report.converter;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.gson.Gson;
import com.opencsv.CSVReader;

public class ReportConverterTabDelimited extends ReportConverterBase {

	private List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
	private Gson gson = new Gson();

	private boolean isHeader(int rowIndex) {
		return rowIndex == 0;
	}

	@Override
	protected void doReadFrom(String path) {
		readFromTabDelimited(path);
	}

	@Override
	protected String doToJson() {
		return this.gson.toJson(this.list);
	}

	private void readFromTabDelimited(String path) {
		CSVReader reader;
		try {
			reader = new CSVReader(new FileReader(path), '\t');
			String[] row;
			String[] header = new String[2];
			int rowIndex = 0;
			while ((row = reader.readNext()) != null) {
				if (isHeader(rowIndex)) {
					header = row;
					rowIndex++;
					continue;
				}
//				if (!skipHeader(rowIndex)) {
//					header = row;
//				} else {
//					rowIndex++;
//					continue;
//				}
				HashMap<String, String> item = new HashMap<String, String>();
				for (int columnIndex = 0; columnIndex < row.length; columnIndex++) {
					item.put(formatHeader(header[columnIndex]), row[columnIndex]);
					
				}
				list.add(item);
				// Object obj = buildItem(row);
				// this.items.add(obj);
				rowIndex++;
			}
			System.out.println("sss");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String formatHeader(String header) {
		return header.replaceAll(" ", "_");
	}
}
